package com.internetCafes.spms.web.customer.bizservice.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.common.utils.entity.page.PageItemDTO;
import com.internetCafes.spms.common.utils.entity.page.PageItemUtil;
import com.internetCafes.spms.common.utils.entity.page.PageItemVO;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.core.exception.RRExceptionCodeEnum;
import com.internetCafes.spms.web.customer.bizservice.customer.IEntCustomerFlowBizService;
import com.internetCafes.spms.web.customer.common.component.msg.impl.MsgComponent;
import com.internetCafes.spms.web.customer.common.cont.CommonConst;
import com.internetCafes.spms.web.customer.common.cont.CustomerConst;
import com.internetCafes.spms.web.customer.entity.customer.Customer;
import com.internetCafes.spms.web.customer.entity.customer.CustomerFlow;
import com.internetCafes.spms.web.customer.entity.user.EntUserInfo;
import com.internetCafes.spms.web.customer.model.customer.CustomerDetailDo;
import com.internetCafes.spms.web.customer.model.customer.CustomerDetailPo;
import com.internetCafes.spms.web.customer.model.customer.flow.CustomerFlowPagingReq;
import com.internetCafes.spms.web.customer.model.customer.flow.CustomerFlowPagingRes;
import com.internetCafes.spms.web.customer.model.customer.flow.FlowExcel;
import com.internetCafes.spms.web.customer.model.customer.flow.FlowExcelReq;
import com.internetCafes.spms.web.customer.service.customer.ICustomerFlowService;
import com.internetCafes.spms.web.customer.service.customer.ICustomerService;
import com.sms.common.util.hutool.core.bean.BeanUtil;
import com.sms.common.util.hutool.core.date.DatePattern;
import com.sms.common.util.hutool.core.date.DateUtil;
import com.sms.common.util.hutool.core.util.ObjectUtil;
import com.sms.common.util.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EntCustomerFlowBizServiceImpl implements IEntCustomerFlowBizService {

    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ICustomerFlowService customerFlowService;
    @Autowired
    private MsgComponent msgComponent;

    @Override
    public List<FlowExcel> flowExcelExport(FlowExcelReq req) {
        LambdaQueryWrapper<CustomerFlow> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(req.getCreateByName())) {
            queryWrapper.like(CustomerFlow::getCreateByName, req.getCreateByName());
        }
        if (ObjectUtil.isNotNull(req.getCustomerId())) {
            queryWrapper.eq(CustomerFlow::getCustomerId, req.getCustomerId());
        }
        queryWrapper.orderByDesc(CustomerFlow::getCreateTime);
        List<CustomerFlow> flowList = customerFlowService.list(queryWrapper);
        return flowList.stream().map(po -> {
                    FlowExcel res = new FlowExcel();
                    res.setCreateByName(po.getCreateByName())
                            .setCreateTime(DateUtil.format(po.getCreateTime(), DatePattern.NORM_DATE_PATTERN))
                            .setActionContent(actionContent(po));
                    return res;})
                .collect(Collectors.toList());
    }

    /**
     * 封装操作内容详情
     */
    private String actionContent(CustomerFlow flowPo) {

        CustomerConst.FlowActionTag action = CustomerConst.FlowActionTag.getTagById(flowPo.getActionTag());
        // 创建
        if (CustomerConst.FlowActionTag.CREATE.equals(action) || CustomerConst.FlowActionTag.DELETE.equals(action)
            || CustomerConst.FlowActionTag.TO_INTENTION.equals(action) || CustomerConst.FlowActionTag.TO_DEAL.equals(action)
            || CustomerConst.FlowActionTag.INTENTION_MOVE.equals(action) || CustomerConst.FlowActionTag.DEAL_MOVE.equals(action) ) {
            return action.getTag();
        }

        return flowPo.getOriginalUserName() + (ObjectUtil.isNotNull(action) ? action.getTag() : "") + flowPo.getTargetUserName();
    }

    @Override
    public PageItemVO<CustomerFlowPagingRes> paging(PageItemDTO<CustomerFlowPagingReq> req) {
        Page<CustomerFlow> flowPageDo = new Page<>(req.getPageNum(), req.getPageSize());
        CustomerFlowPagingReq conditions = req.getConditions();
        QueryWrapper<CustomerFlow> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(conditions)) {
            if (StrUtil.isNotBlank(conditions.getCreateByName())) {
                queryWrapper.like("xcf.create_by_name", conditions.getCreateByName());
            }
            if (ObjectUtil.isNotNull(conditions.getCustomerId())) {
                queryWrapper.eq("xcf.customer_id", conditions.getCustomerId());
            }
        }
        PageItemUtil.order(req, queryWrapper);
        Page<CustomerFlow> pagingPo = customerFlowService.paging(flowPageDo, queryWrapper);

        PageItemVO<CustomerFlowPagingRes> pagingRes = PageItemUtil.toPageItemVO(pagingPo, new PageItemVO<>());
        pagingRes.setRecords(
                pagingPo.getRecords()
                        .stream()
                        .map(po -> {
                            CustomerFlowPagingRes res = new CustomerFlowPagingRes();
                            BeanUtil.copyProperties(po, res);
                            res.setCreateTime(DateUtil.format(po.getCreateTime(), DatePattern.NORM_DATETIME_PATTERN));
                            return res;
                        }).collect(Collectors.toList())
        );
        return pagingRes;
    }

    @Override
    public boolean remove(Long customerId) {
        // 获取客户信息
        CustomerDetailPo customerDetailPo = customerService.customerPoDetail(new CustomerDetailDo().setId(customerId));

        // 验证客户信息
        if (ObjectUtil.isNull(customerDetailPo)) {
            throw new RRException(RRExceptionCodeEnum.DATA_NOT_EXIST);
        }

        // 记录流转记录 转意向
        CustomerFlow customerFlowDo = new CustomerFlow();
        customerFlowDo.setCustomerId(customerId)
                .setActionTag(
                        customerDetailPo.getTypeId().equals(CustomerConst.TypeEnum.DEAL.getId()) ?
                        CustomerConst.FlowActionTag.DEAL_MOVE.getId() : CustomerConst.FlowActionTag.INTENTION_MOVE.getId())
                .setTargetUserId(customerDetailPo.getFollowUserId())
                .setTargetUserName(customerDetailPo.getFollowUserName());
        customerFlowService.save(customerFlowDo);
        Customer customer = new Customer();
        BeanUtil.copyProperties(customerDetailPo, customer);
        boolean result = customerService.updateById(new Customer().setId(customerId).setTypeId(CustomerConst.TypeEnum.GENERAL.getId()));
        if (result) {
            msgComponent.customerRemove(customer);
        }
        return result;
    }

    @Override
    public boolean interest(Long customerId) {
        // 获取客户信息
        CustomerDetailPo customerDetailPo = customerService.customerPoDetail(new CustomerDetailDo().setId(customerId));

        // 验证客户信息
        if (ObjectUtil.isNull(customerDetailPo)) {
            throw new RRException(RRExceptionCodeEnum.DATA_NOT_EXIST);
        }

        // 限制：成交不能转意向
        if (CustomerConst.TypeEnum.DEAL.getId().equals(customerDetailPo.getTypeId())) {
            throw new RRException(RRExceptionCodeEnum.CUSTOMER_DEAL_CAN_NOT_TO_INTENTION);
        }

        if (CustomerConst.TypeEnum.INTENTION.getId().equals(customerDetailPo.getTypeId())) {
            if (!customerDetailPo.getFollowUserId().equals(ShiroUtils.getUserId())) {
                throw new RRException(RRExceptionCodeEnum.CUSTOMER_IS_OTHER_INTENTION);
            }
            throw new RRException(RRExceptionCodeEnum.CUSTOMER_IS_INTENTION);
        }

        // 记录流转记录 转意向
        CustomerFlow customerFlowDo = new CustomerFlow();
        customerFlowDo.setCustomerId(customerId)
                .setActionTag(CustomerConst.FlowActionTag.TO_INTENTION.getId())
                .setTargetUserId(customerDetailPo.getFollowUserId())
                .setTargetUserName(customerDetailPo.getFollowUserName());
        customerFlowService.save(customerFlowDo);

        // 修改客户记录信息 跟进人修改为当前用户
        boolean result = customerService.updateById(
                new Customer()
                        .setId(customerId)
                        .setTypeId(CustomerConst.TypeEnum.INTENTION.getId())
                        .setFollowUserId(ShiroUtils.getUserId()));
        if (result) {
            EntUserInfo entUserInfo = new EntUserInfo();
            BeanUtil.copyProperties(ShiroUtils.getUserEntity(), entUserInfo);
            msgComponent.customerToInterest(customerDetailPo, entUserInfo);
        }
        return result;
    }

    @Override
    public boolean deal(Customer customerPo) {
        // 验证客户信息
        if (ObjectUtil.isNull(customerPo)) {
            throw new RRException(RRExceptionCodeEnum.DATA_NOT_EXIST);
        }

        // 限制：成交已经是成交
        if (CustomerConst.TypeEnum.DEAL.getId().equals(customerPo.getTypeId())) {
            throw new RRException(RRExceptionCodeEnum.CUSTOMER_IS_DEAL);
        }

        // 意向客户 判断是否是自己的
        if (CustomerConst.TypeEnum.INTENTION.getId().equals(customerPo.getTypeId())) {
            if (!customerPo.getFollowUserId().equals(ShiroUtils.getUserId())) {
                throw new RRException(RRExceptionCodeEnum.CUSTOMER_IS_OTHER_INTENTION);
            }
        }

        // 记录流转记录 转成交
        CustomerFlow customerFlowDo = new CustomerFlow();
        customerFlowDo.setCustomerId(customerPo.getId())
                .setActionTag(CustomerConst.FlowActionTag.TO_DEAL.getId())
                .setTargetUserId(ShiroUtils.getUserId())
                .setTargetUserName(ShiroUtils.getUserEntity().getNickName());
        customerFlowService.save(customerFlowDo);

        Customer customerUpdateDo = new Customer()
                .setId(customerPo.getId()).setTypeId(CustomerConst.TypeEnum.DEAL.getId())
                .setRegularFlag(CommonConst.FlagEnum.IS.getId())
                .setFollowUserId(ShiroUtils.getUserId());

        // 修改客户信息状态
        boolean result = customerService.updateById(customerUpdateDo);

        if (result) {
            EntUserInfo entUserInfo = new EntUserInfo();
            BeanUtil.copyProperties(ShiroUtils.getUserEntity(), entUserInfo);
            msgComponent.customerToDeal(customerPo, entUserInfo);
        }
        return result;
    }
}
